var async = require('async');
var AV = require('leanengine');
var Q = require('q');
var CartM = AV.Object.extend('DiyCartProduct');
//商品详情相关模型信息
var ProductM = AV.Object.extend('Product');
var queryPro = new AV.Query(ProductM);
var queryCart = new AV.Query(CartM);


module.exports = {

    get:function(uid,pid){

        var deferred = Q.defer();

        var queryCart = new AV.Query(CartM);
        queryCart.equalTo('uid',uid+'');
        if(pid){
            queryCart.equalTo('pid',pid+'');
        }
        queryCart.find().then(function(cartList){
            deferred.resolve(cartList);
        }).catch(function(err){
            deferred.reject(err);
        });

        return deferred.promise;
    },
    /**
     * 商品添加至购物车方法
     */
    add:function(uid,pid,psid,number,price){
        if(!pid) {
            return new AV.Promise.error({code:251});     //商品编号不能为空
        }

        if(!psid) {
            return new AV.Promise.error({code:255});     //商品规格编号不能为空
        }

        if(!number) {
            return new AV.Promise.error({code:256});     //商品数量不能为空
        }

        if(!uid) {
            return new AV.Promise.error({code:250});     //用户编号不能为空
        }
        var promise = new AV.Promise();

        //创建购物车的查询实例
        var query = new AV.Query(CartM);

        async.waterfall([
            function(callback){
                //根据pid,psid,uid获取该对象
                query.equalTo('pid',pid+"");
                //query.equalTo('psid',psid+"");
                query.equalTo('uid',uid+"");
                query.first().then(function(res){
                    callback(null,res);
                }).catch(function(err){
                    callback({code:9999,reason:err});    //code:9999 系统错误
                });
            }, function(res,callback){
                if(!res || res.length<1){
                    //用户之前没有添加该商品到购物车
                    var obj = new CartM();
                    obj.set('number',parseInt(number));
                    obj.set('uid',uid+"");
                    obj.set('pid',pid+"");
                    obj.set('psid',psid+"");
                    obj.set('price',parseFloat(price));
                    obj.set('amountprice',parseFloat(price)*parseInt(number));
                    obj.set('checked',true);
                    obj.save().then(function(cartPro){
                        callback(null,{code:0,objectId:cartPro.id});       //添加购物车成功
                    }).catch(function(err){
                        callback({code:9999,reason:err});//code:9999 系统错误
                    });
                }else{
                    //用户之前已经添加过该商品到购物车 那就修改数量和金额
                    res.set('number',parseInt(number));
                    res.set('price',parseFloat(price));
                    res.set('amountprice',parseFloat(price)*parseInt(number));
                    res.save().then(function(cartPro){
                        callback(null,{code:0,objectId:cartPro.id,numbser:number});       //添加购物车成功,返回numbser：添加的数量
                    }).catch(function(err){
                        callback({code:9999,reason:err});//code:9999 系统错误
                    });
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    //查询用户的购物车数据
    // getProductList	!userid:String	array<CartProduct购物车数据
    getProductList:function(userid,checked){
        if(userid){
            var promise = new AV.Promise();
            async.waterfall([
                function(callback){
                    var queryCart = new AV.Query(CartM);
                    queryCart.equalTo('uid',userid);
                    if(checked==true){
                        queryCart.equalTo('checked',checked);
                    }
                    queryCart.find().then(function(cartList){
                        callback(null, cartList);
                    }).catch(function(err){
                        callback({code:9999,reason:err});
                    });
                },
                function(cartList,callback){
                    if(!cartList || cartList.length<1){
                        //购物车内没有数据
                        callback(null, {code:0,rows:0,data:{}});
                    }
                    var index = cartList.length;
                    async.eachSeries(cartList,function(each,callback1){
                        queryPro.get(each.get('pid')).then(function(product){
                            each.set('product',product);
                            callback1(null, cartList);

                        }).catch(function(err){
                            callback({code:9999,reason:err});
                        });
                    },function(){
                        callback(null, {code:0,rows:cartList.length,data:cartList});
                    });
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("userid should not be empty!");
        }
    },
    //删除购物车中商品 !cartproductid:string
    //删除购物车中商品后需要增加库存
    //已完成
    delCartProduct:function(objectid){
        if(objectid){
            var promise = new AV.Promise();
            //根据objectid删除对应的内容
            async.waterfall([
                function(callback){
                    queryCart.get(objectid).then(function(res){
                        callback(null,res);
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback({code:9901,reason:err});
                    });
                },
                function(res,callback){
                    res.destroy().then(function(isSuccess){
                        var addInventory = 0;
                        addInventory = parseInt(isSuccess.get('number') );
                        callback(null,res,addInventory);
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback({code:9902,reason:err});
                    });
                },
                function(res,addInventory,callback){
                    //根据购物车中的pid获取商品表中的记录
                    queryPro.get(res.get('pid')).then(function(info){
                        callback(null, res, info, addInventory);
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback({code:9903,reason:err});
                    });
                },
                function( res, info, addInventory,callback){
                    //增加库存
                    var spec = info.get('spec');
                    var specInfo = spec[res.get('psid')];
                    //历史库存
                    var inventory = specInfo.inventory;
                    //新库存
                    var newInventory = parseInt(inventory) + parseInt(addInventory);
                    inventory = newInventory;
                    specInfo['inventory'] = inventory+'';   //需要将库存转换成string类型
                    info.set('spec',spec);
                    info.save().then(function(){
                        callback(null,{code:0,msg:'删除购物车商品成功'});
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback({code:9904,reason:err});
                    });
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("objectid should not be empty!");
        }
    },
    //查询购物车被选中商品货物总价
    getGoodsPrice:function(userid){
        if(userid){
            var promise = new AV.Promise();
            async.waterfall([
                function(callback){
                    var queryCart = new AV.Query(CartM);
                    queryCart.equalTo('uid',userid);
                    queryCart.equalTo('checked',true);
                    queryCart.find().then(function(res){
                        callback(null, res);
                    }).catch(function(err){
                        callback({code:9999,reason:err});
                    });
                },
                function(res,callback){
                    //遍历每条记录，根据商品id和规格id获取价格，再用价格*数量，得到总价
                    if(!res || res.length<1){
                        return callback(null,{code:0,msg:'购物车没有选中商品',GoodsPrice:0});
                    }
                    var amount = 0;
                    var index = res.length;
                    res.forEach(function(info){

                        queryPro.get(info.get('pid')).then(function(proInfo){
                            var spec = proInfo.get('spec');
                            var psid = spec[info.get('psid')];

                            amount =amount + info.get('amountprice');
                            index--;
                            if(index === 0){
                                callback(null, {code:1,msg:'查询商品总价成功',GoodsPrice:amount});
                            }
                        }).catch(function(err){
                            callback({code:9999,reason:err});
                        });
                    });
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            })
            return promise;
        }else{
            return new AV.Promise.error("userid should not be empty!");
        }
    },
    /*
     * 订单生成后清除商品数据
     * Add By James 2016-01-31
     * params:userid (用户编号)
     *
     */
    delCartPro:function(userid){

        if(!userid){
            return new AV.Promise.error({code:458});        //用户编号不能为空
        }

        var promise = new AV.Promise();

        async.waterfall([
            function(callback){
                var queryCart = new AV.Query(CartM);
                queryCart.equalTo('uid',userid);
                queryCart.find().then(function(cartList){
                    callback(null, cartList);
                }).catch(function(err){
                    callback({code:9999,reason:err});
                });
            },
            function(cartList,callback){
                if(!cartList || cartList.length<1){
                    //购物车内没有数据
                    callback(null,{code:0});
                }

                cartList.forEach(function (val) {
                    val.destroy().then(function(){

                    }).catch(function(err){
                        callback({code:9999,reason:err});       //code:9999 系统错误
                    });
                });


                callback(null,{code:0});
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    }
}